﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.ComponentModel;

namespace eHouse
{
    public partial class WaitingScreen : PhoneApplicationPage
    {
        //Task to be executed while waiting in Waiting Screen
        public delegate void WaitingTask();
        public static WaitingTask waitingTask = null;
        public static string nextWindow = null;
        public static string savedWindow = "/MainPage.xaml";
        public static bool fromDorm = false;

        private readonly object _locker = new object();
        private bool terminate;
        private bool Terminate
        {
            get
            {
                lock (_locker)
                {
                    return terminate;
                }
            }
            set
            {
                lock (_locker)
                {
                    terminate = value;
                }
            }
        }

        private BackgroundWorker backTask = null;

        public WaitingScreen()
        {
            InitializeComponent();
            WaitingImage.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("WaitingImage" + App.IconToUse + ".png", UriKind.RelativeOrAbsolute));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            backTask = new BackgroundWorker();
            backTask.WorkerSupportsCancellation = true;
            backTask.DoWork += new DoWorkEventHandler((object send, DoWorkEventArgs dwea) =>
            {
                WaitingScreen.waitingTask();
            });
            backTask.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
            backTask.RunWorkerAsync();
        }

        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!Terminate && !e.Cancelled && e.Error == null)
            {
                Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri(WaitingScreen.nextWindow, UriKind.RelativeOrAbsolute)); });
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            backTask.CancelAsync();

            Terminate = true;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            NavigationService.RemoveBackEntry();
            if (fromDorm)
            {
                NavigationService.RemoveBackEntry();
                fromDorm = false;
            }
        }
    }
}